package edu.neumont.pro180._2009_q2.network;

import java.awt.Point;
import edu.neumont.pro180._2009_q2.Board;
import edu.neumont.pro180._2009_q2.Player;
import edu.neumont.pro180._2009_q2.chess.ChessGame;
import edu.neumont.pro180._2009_q2.interfaces.ICommand;

public class NetworkGame extends ChessGame {

	// utility methods designed to help interface w/ tyler's bootstrapping
	// program.
	public static Point stringToPoint(String s) {
		s = s.toUpperCase();
		char c = s.charAt(0);
		int x = (int)c - 65;
		int y = Integer.parseInt(s.substring(1)) - 1;

		Point p = new Point(x,y);
		
		return p;
	}

	protected String moveToString(ICommand move) {		
		//get the start point
		Point start = this.board.getPoint(move.getOriginalSquare());
		
		//get the end point
		Point end = this.board.getPoint(move.getDestination());
		
		//convert the start point to a string
		char charStartX = (char)(start.x + 65);
		String startX = String.valueOf(charStartX);
		String startY = String.valueOf(start.y + 1);
		
		String startString = startX + startY;
		
		//convert the end point to a string
		char charEndX = (char)(end.x + 65);
		String endX = String.valueOf(charEndX);
		String endY = String.valueOf(end.y + 1);
		
		String endString = endX + endY;
		
		return startString + " " + endString;
	}

	public void playGame(String player) {
		// setup the board
		try {
			this.board = new Board(this.rowCount, this.columnCount);
		} catch (IllegalArgumentException e) {
			throw new IllegalStateException(
					"Rows/Columns weren't set up correctly, cannot play game",
					e);
		}

		// set up the players
		Player us = new AI(this);
		Player opponent = new Opponent();

		// populate the board
		board.addPlayer(us);
		board.addPlayer(opponent);
		populateChessBoard(board, us, opponent);

		// set the active player based on arguments received
		if (player.equals("white")) {
			this.board.setActivePlayer(us);
		} else if (player.equals("black")) {
			this.board.setActivePlayer(opponent);
		}

		while (true) {
			if (this.isInCheckmate(this.board.getActivePlayer(), this.board))
				break;

			// get the active players move
			Player activePlayer = this.board.getActivePlayer();
			ICommand move = activePlayer.getNextMove();

			// execute the move
			this.board.doMove(move);

			// if we're the active player
			if (this.board.getActivePlayer().equals(us)) {
				// send the move
				System.out.println(this.moveToString(move));
				// switch the active player to the opponent
				this.board.setActivePlayer(opponent);
			} else if (!this.board.getActivePlayer().equals(us)) {
				// switch the active player to us
				this.board.setActivePlayer(us);
			}

		}
	}
	
	public static void main(String[] args) {
		NetworkGame game = new NetworkGame();
		game.playGame(args[0]);
	}
}
